from collections import defaultdict
import pymongo
import time
import json
import requests
import redis
from wxpy import Bot, Group, TEXT, Tuling
from datetime import date, timedelta

# 127
client_127 = pymongo.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
db_127 = client_127.cs_recharge
coll_127 = db_127.rechange
conn = redis.Redis()


def get_ts():
    return str(time.time()).replace('.', '')[:13]


def get_all():
    today = date.today()
    today = today.strftime('%Y%m%d')
    # 127

    suc_count = coll_127.aggregate([{"$match": {"orderstate": "0", "orderdate": today}},
                                    {"$group": {"_id": "$tel_type", "成功金额": {"$sum": {"$toInt": "$amount"}},
                                                "成功笔数": {"$sum": 1}}}])

    s = ""
    summany = 0
    for i in suc_count:
        s += '%s： %d。' % (i['_id'], i['成功金额'])
        summany += i['成功金额']
    s += "总金额：%d" % summany
    return s

def get_unknow():
    # 联通
    res = defaultdict(int)
    today = date.today()
    today = today.strftime('%Y%m%d')
    # 127

    suc_count = coll_127.aggregate([{"$match": {"orderstate": "0", "orderdate": today, 'tel_type': "unicom",
                                                "merchantid": "M2018081416281534235296"}},
                                    {"$group": {"_id": None, "成功金额": {"$sum": {"$toInt": "$amount"}},
                                                "成功笔数": {"$sum": 1}}}])
    if suc_count:
        res.update(list(suc_count)[0])
        res.pop('_id')

    return res


def get_cmcc_amount():
    res = defaultdict(int)
    today = date.today()
    today = today.strftime('%Y%m%d')
    # 127

    suc_count = coll_127.aggregate([{"$match": {"orderstate": "0", "orderdate": today, 'tel_type': "cmcc",
                                                "merchantid": "M2018081416281534235296"}},
                                    {"$group": {"_id": None, "成功金额": {"$sum": {"$toInt": "$amount"}},
                                                "成功笔数": {"$sum": 1}}}])

    suc_count = list(suc_count)
    if suc_count:
        res.update(suc_count[0])
        res.pop('_id')
    else:
        res['成功金额'] = 0
        res['成功笔数'] = 0

    fail_count = coll_127.aggregate([{"$match": {"orderstate": "0", "orderdate": today, 'tel_type': "cmcc",
                                                 "message": "充值失败", "merchantid": "M2018081416281534235296"}},
                                     {"$group": {"_id": None, "充值失败金额": {"$sum": {"$toInt": "$amount"}},
                                                 "充值失败笔数": {"$sum": 1}}}])
    fail_count = list(fail_count)
    if fail_count:
        res.update(fail_count[0])
        if res['成功金额'] > 0:
            res['返销比例'] = "%.4f" % (res['充值失败金额'] / res['成功金额'])
        res.pop('_id')

    return res


def get_ctcc_amount():
    res = defaultdict(int)
    today = date.today()
    today = today.strftime('%Y%m%d')
    # 127

    suc_count = coll_127.aggregate([{"$match": {"orderstate": "0", "orderdate": today, 'tel_type': "ctcc",
                                                "merchantid": "M2018081416281534235296"}},
                                    {"$group": {"_id": None, "成功金额": {"$sum": {"$toInt": "$amount"}},
                                                "成功笔数": {"$sum": 1}}}])
    suc_count = list(suc_count)
    if suc_count:
        res.update(suc_count[0])
        res.pop('_id')

    if res:
        return res
    else:
        return {"成功金额": 0, "成功笔数": 0}


while True:
    now = time.time()
    try:
        res = get_unknow()
        conn.hmset("unicom_unkonw", res)
        cmcc_res = get_cmcc_amount()
        conn.hmset("cmcc_amount", cmcc_res)
        ctcc_res = get_ctcc_amount()
        conn.hmset("ctcc_amount", ctcc_res)
        print(time.time() - now)
        print(res)
        print(cmcc_res)
        print(ctcc_res)
        all_res = get_all()
        print(all_res)
        conn.set("all_recharge", all_res)

    except Exception as e:
        print(e)

    # message = "; ".join(["%s:%s" % (k, v) for k, v in res.items()])
    # message = "各省未知数量：" + message
    # group.send(message)
    time.sleep(5 * 1)
